package com.maple.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * <p></p>
 *
 * @author maple
 */
@Configuration
public class ThreadPoolConfig {

    @Value("${thread-pool.core-pool-size}")
    private int corePoolSize;

    @Value("${thread-pool.max-pool-size}")
    private int maxPoolSize;

    @Value("${thread-pool.queue-capacity}")
    private int queueCapacity;

    public static final String SEND_MQ_TOPIC = "sendMqTopic";

    private ThreadPoolTaskExecutor getExecutor(int maxPoolSize, String threadNamePrefix) {
        ThreadPoolTaskExecutor asyncTaskExecutor = new ThreadPoolTaskExecutor();
        asyncTaskExecutor.setMaxPoolSize(maxPoolSize);
        asyncTaskExecutor.setCorePoolSize(maxPoolSize);
        asyncTaskExecutor.setThreadNamePrefix(threadNamePrefix + "-");
        asyncTaskExecutor.initialize();
        return asyncTaskExecutor;
    }

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("my-thread-pool-");
        executor.initialize();
        return executor;
    }

    @Bean(SEND_MQ_TOPIC)
    public AsyncTaskExecutor sendMqTopic() {
        return this.getExecutor(10, SEND_MQ_TOPIC);
    }
}
